package com.ly.thread;
import java.util.*;
import java.util.concurrent.TimeUnit;
import	java.util.concurrent.locks.ReentrantReadWriteLock;
import	java.util.concurrent.locks.ReadWriteLock;

class MyCache {

    private ReadWriteLock lock = new ReentrantReadWriteLock();

    private Map<String,String> map = new HashMap<>();

    public void put(String key,String value) {
        try {
            lock.writeLock().lock();
            map.put(key,value);
            System.out.println(Thread.currentThread().getName() +"writing");
            TimeUnit.MILLISECONDS.sleep(500);
            System.out.println(Thread.currentThread().getName() +"written");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.writeLock().unlock();
        }
    }

    public void get(String key) {
        try {
            lock.readLock().lock();
            System.out.println(Thread.currentThread().getName() +"reading");
            TimeUnit.MILLISECONDS.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            System.out.println(Thread.currentThread().getName() +map.get(key));
            lock.readLock().unlock();
        }

    }
}

public class ReadWriteLockDemo {

    public static void main(String[] args) {

        MyCache myCache = new MyCache();
        for(int i=0;i<5;i++) {
            final int j = i;
            new Thread(() -> {myCache.put(j+"",j+"");},String.valueOf(i)).start();
        }
        for(int i=0;i<5;i++) {
            final int j = i;
            new Thread(() -> {myCache.get(j+"");},String.valueOf(i)).start();
        }
    }
}
